package com.ruoyi.app.business.user;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.app.business.account.CompanyAccountBusiness;
import com.ruoyi.app.business.account.LaborAccountBusiness;
import com.ruoyi.app.business.check.CheckRecordBusiness;
import com.ruoyi.app.business.code.CheckCodeBusiness;
import com.ruoyi.app.business.code.InviteCodeBusiness;
import com.ruoyi.app.business.dict.DictBusiness;
import com.ruoyi.app.business.login.TokenBusiness;
import com.ruoyi.app.business.message.MessageBusiness;
import com.ruoyi.app.business.project.FavouriteBusiness;
import com.ruoyi.app.business.project.ProjectLaborBusiness;
import com.ruoyi.app.business.project.ProjectSettleBusiness;
import com.ruoyi.app.business.reward.LaborRewardBusiness;
import com.ruoyi.app.business.score.ScoreBusiness;
import com.ruoyi.app.company.CompanyBusiness;
import com.ruoyi.app.config.platform.PlatFormConfig;
import com.ruoyi.app.config.util.UserUtil;
import com.ruoyi.app.converter.CompanyConverter;
import com.ruoyi.app.converter.UserConverter;
import com.ruoyi.app.domain.company.CompanyCheckResult;
import com.ruoyi.app.domain.labor.LaborInfo;
import com.ruoyi.app.domain.labor.LaborInfoDetail;
import com.ruoyi.app.domain.my.DemanderMy;
import com.ruoyi.app.domain.my.LaborMy;
import com.ruoyi.app.domain.my.PlatformMy;
import com.ruoyi.app.domain.register.CompanyRegister;
import com.ruoyi.app.domain.user.UserCheckResult;
import com.ruoyi.app.domain.user.add.UserInfoAdd;
import com.ruoyi.app.domain.user.add.UserInfoView;
import com.ruoyi.app.domain.user.inviteCode.InviteCode;
import com.ruoyi.app.domain.user.inviteCode.InviteCodeParam;
import com.ruoyi.app.domain.user.update.UpdatePwd;
import com.ruoyi.common.core.enums.YesNoEnum;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.core.utils.pwd.PwdUtil;
import com.ruoyi.common.core.web.page.CommonPageInfo;
import com.ruoyi.service.account.entity.CompanyAccountEntity;
import com.ruoyi.service.account.entity.LaborAccountEntity;
import com.ruoyi.service.check.entity.CheckRecordEntity;
import com.ruoyi.service.company.entity.CompanyEntity;
import com.ruoyi.service.company.enums.CheckStatusEnum;
import com.ruoyi.service.dict.entity.DictDataEntity;
import com.ruoyi.service.dict.enums.DictTypeEnum;
import com.ruoyi.service.message.enums.MessageTemplateEnum;
import com.ruoyi.service.project.service.ProjectService;
import com.ruoyi.service.project.service.ProjectSettleService;
import com.ruoyi.service.score.entity.LaborScoreEntity;
import com.ruoyi.service.score.service.CompanyScoreService;
import com.ruoyi.service.user.entity.LaborExtEntity;
import com.ruoyi.service.user.entity.UserEntity;
import com.ruoyi.service.user.enums.UserTypeEnum;
import com.ruoyi.service.user.model.UserInfoModel;
import com.ruoyi.service.user.query.LaborPopQuery;
import com.ruoyi.service.user.query.LaborQuery;
import com.ruoyi.service.user.query.UserQuery;
import com.ruoyi.service.user.service.LaborExtService;
import com.ruoyi.service.user.service.UserService;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;


@Slf4j
@Component
public class UserBusiness {

  @Resource
  private UserService userService;
  @Resource
  private LaborExtService laborExtService;
  @Resource
  private CompanyBusiness companyBusiness;
  @Resource
  private CompanyAccountBusiness companyAccountBusiness;
  @Resource
  private CompanyScoreService companyScoreService;
  @Resource
  private ScoreBusiness scoreBusiness;
  @Resource
  private DictBusiness dictBusiness;
  @Resource
  private TransactionTemplate transactionTemplate;
  @Resource
  private TokenBusiness tokenBusiness;
  @Resource
  private InviteCodeBusiness inviteCodeBusiness;
  @Resource
  private MessageBusiness messageBusiness;
  @Resource
  private PlatFormConfig platformConfig;
  @Resource
  private ProjectSettleService projectSettleService;

  @Lazy
  @Resource
  private ProjectService projectService;

  @Lazy
  @Resource
  private FavouriteBusiness favouriteBusiness;

  @Lazy
  @Resource
  private ProjectLaborBusiness projectLaborBusiness;

  @Lazy
  @Resource
  private LaborRewardBusiness laborRewardBusiness;

  @Lazy
  @Resource
  private LaborAccountBusiness laborAccountBusiness;

  @Lazy
  @Resource
  private ProjectSettleBusiness projectSettleBusiness;
  @Resource
  private CheckRecordBusiness checkRecordBusiness;
  @Resource
  private CheckCodeBusiness checkCodeBusiness;

  public CommonPageInfo<LaborInfo> listLabor(LaborQuery laborQuery) {
    CommonPageInfo<UserEntity> pageInfo = PageUtils.startPage(laborQuery.getPageNum(),
        laborQuery.getPageSize());
    pageInfo.initData(Optional.ofNullable(userService.listLaborByQuery(laborQuery))
        .orElseGet(ArrayList::new));
    //获得附加信息
    return convert(pageInfo);
  }

  private String getPostName(Map<String, DictDataEntity> dictMap, String post) {
    final DictDataEntity dictDataEntity = dictMap.get(post);
    if (Objects.nonNull(dictDataEntity)) {
      return dictDataEntity.getDictDesc();
    }
    return "";
  }

  private Integer getStartScore(Map<Long, LaborScoreEntity> laborScoreMap, Long laborId) {
    final LaborScoreEntity laborScoreEntity = laborScoreMap.get(laborId);
    if (Objects.nonNull(laborScoreEntity)) {
      return laborScoreEntity.getAvgScore();
    }
    return 0;
  }

  /**
   * 绑定公司
   */
  public void bindCompany(CompanyRegister companyRegister) {
    //校验公司统一社会信用码,是否已经注册
    if (companyBusiness.companyExist(companyRegister.getUsci())) {
      throw new ServiceException("公司已注册,请联系管理员");
    }
    final CompanyEntity companyEntity = CompanyConverter.INSTANCE.toCompanyEntity(companyRegister);
    companyEntity.setManager(UserUtil.getUserId())
        .setCreateBy(UserUtil.getUserId())
        .setCreateTime(LocalDateTime.now())
        .setUpdateBy(UserUtil.getUserId())
        .setUpdateTime(LocalDateTime.now());
    companyBusiness.saveCompany(companyEntity);
    //补充必要信息
//    transactionTemplate.executeWithoutResult(status -> {
//      companyEntity.setManager(UserUtil.getUserId());
//
//    });
  }

  /**
   * 审核公司
   */
  @Transactional(rollbackFor = Exception.class)
  public void checkCompany(CompanyCheckResult checkResult) {
    if (CheckStatusEnum.DENIED.eqCode(checkResult.getChekResult())) {
      CommonUtils.assertsFieldHasText(checkResult.getComment(), "请填写审核结果");
    }
    //公司审核
    final CompanyEntity company = CommonUtils.requireNotNull(
        companyBusiness.getById(checkResult.getComId()),
        "公司Id不合法");
    if (!CheckStatusEnum.CHECKING.eqCode(company.getStatus())) {
      throw new ServiceException("公司已被审核");
    }
    final CheckStatusEnum checkStatusEnum = CheckStatusEnum.valueOfCode(
        checkResult.getChekResult());
    company.setCheckBy(UserUtil.getUsername())
        .setCheckTime(LocalDateTime.now())
        .setStatus(checkStatusEnum.getCode())
        .setCheckRemark(
            Optional.ofNullable(checkResult.getComment()).orElse(checkStatusEnum.getDesc()))
        .setUpdateBy(UserUtil.getUserId())
        .setUpdateTime(LocalDateTime.now());
    companyBusiness.updateById(company);
    final CheckRecordEntity checkRecordEntity = checkRecordBusiness.addCheckRecord(checkResult);
    final Long manager = company.getManager();
    MessageTemplateEnum templateEnum = CheckStatusEnum.isPassed(checkStatusEnum.getCode())
        ? MessageTemplateEnum.A14
        : MessageTemplateEnum.A15;
    messageBusiness.sendPlatformMsg(templateEnum, new HashMap<String, String>() {{
      put("checkRemark", company.getCheckRemark());
    }}, String.valueOf(checkRecordEntity.getId()), manager);
    if (CheckStatusEnum.isPassed(checkStatusEnum.getCode())) {
      //构建公司账户信息
      companyAccountBusiness.initCompanyAccount(company);
      //初始话公司评分表
      companyScoreService.initScore(company);
      //更新用户缓存
      tokenBusiness.refreshUser(manager);
    }

  }

  @Transactional(rollbackFor = Exception.class)
  public void checkLabor(UserCheckResult checkResult) {
    if (CheckStatusEnum.DENIED.eqCode(checkResult.getChekResult())) {
      CommonUtils.assertsFieldHasText(checkResult.getComment(), "请填写审核结果");
    }
    final UserEntity userInfo = CommonUtils.requireNotNull(
        userService.getById(checkResult.getUserId()), "用户Id不存在");
    if (!CheckStatusEnum.CHECKING.eqCode(userInfo.getStatus())) {
      throw new ServiceException("用户已被审核");
    }
    final CheckStatusEnum checkStatusEnum = CheckStatusEnum.valueOfCode(
        checkResult.getChekResult());
    userInfo.setStatus(checkStatusEnum.getCode())
        .setUpdateBy(UserUtil.getUsername())
        .setUpdateTime(LocalDateTime.now());
    userService.updateById(userInfo);
    checkRecordBusiness.addCheckRecord(checkResult);
    tokenBusiness.refreshUser(userInfo);
  }

  public UserInfoModel getLoginUserInfo() {
    return UserUtil.getLoginUserMasking();
  }

//  public List<UserEntity> getListByIds(List<Long> userList) {
//    return userService.listByIds(userList);
//  }

  public List<UserEntity> listByIds(List<Long> userIds) {
    if (CollUtil.isEmpty(userIds)) {
      return new ArrayList<>();
    }
    return userService.listByIds(userIds);
  }


  public UserEntity getById(@NotBlank(message = "制作者用户ID不能为空") Long userId) {
    return userService.getById(userId);
  }

  public InviteCode createInviteCode(InviteCodeParam inviteCodeParam) {
    return inviteCodeBusiness.createInviteCode(inviteCodeParam);
  }

  public void userDelete(Long userId, Integer deleteFlag) {
    final UserEntity user = CommonUtils.requireNotNull(userService.getById(userId),
        "用户Id不存在");
    if (user.getDelFlag().equals(deleteFlag)) {
      throw new ServiceException("用户已注销");
    }
    user.setDelFlag(deleteFlag)
        .setUpdateBy(UserUtil.getUsername())
        .setUpdateTime(LocalDateTime.now());
    userService.updateById(user);
    tokenBusiness.refreshUser(user);
  }

  public void userBan(Long userId, Integer banFlag) {
    final UserEntity user = CommonUtils.requireNotNull(userService.getById(userId),
        "用户Id不存在");
    if (user.getBanFlag().equals(banFlag)) {
      if (YesNoEnum.YES.eqCode(banFlag)) {
        throw new ServiceException("用户已封号");
      } else {
        throw new ServiceException("用户已解封");
      }
    }
    user.setBanFlag(banFlag)
        .setUpdateBy(UserUtil.getUsername())
        .setUpdateTime(LocalDateTime.now());
    userService.updateById(user);
    tokenBusiness.refreshUser(user);
  }

  public void userAuth(Long userId, Integer authFlag) {
    final UserEntity user = CommonUtils.requireNotNull(userService.getById(userId),
        "用户Id不存在");
    if (user.getAuthFlag().equals(authFlag)) {
      if (YesNoEnum.YES.eqCode(authFlag)) {
        throw new ServiceException("用户已认证");
      } else {
        throw new ServiceException("用户已解除认证");
      }
    }
    user.setAuthFlag(authFlag)
        .setUpdateBy(UserUtil.getUsername())
        .setUpdateTime(LocalDateTime.now());
    transactionTemplate.executeWithoutResult(status -> {
      userService.updateById(user);
      //
      final MessageTemplateEnum messageTemplateEnum = YesNoEnum.YES.eqCode(authFlag) ?
          MessageTemplateEnum.A10 : MessageTemplateEnum.A11;
      messageBusiness.sendPlatformMsg(messageTemplateEnum, null,
          String.valueOf(UserUtil.getUserId()), userId);
    });
    tokenBusiness.refreshUser(user);
  }


  public List<LaborInfo> selectLabor(LaborPopQuery popQuery) {
    //默认1000行记录
    PageUtils.startPage(1, 1000);
    final List<UserEntity> userEntities = Optional.ofNullable(
            userService.selectLaborByQuery(popQuery))
        .orElseGet(ArrayList::new);
    return userEntities.stream().map(UserConverter.INSTANCE::toLaborInfo)
        .collect(Collectors.toList());
  }

  public List<LaborInfo> selectProjectLeader(LaborPopQuery popQuery) {
    //默认1000行记录
    PageUtils.startPage(1, 1000);
    final List<UserEntity> userEntities = Optional.ofNullable(
            userService.selectProjectLeader(popQuery))
        .orElseGet(ArrayList::new);
    return userEntities.stream().map(UserConverter.INSTANCE::toLaborInfo)
        .collect(Collectors.toList());
  }

  @Transactional(rollbackFor = Exception.class)
  public void addUserByDemander(UserInfoAdd userInfo) {
    final UserInfoModel loginUser = UserUtil.getLoginUser();
    //1 数据校验
    checkUser(userInfo);
    //2 添加用户
    final UserEntity userEntity = UserConverter.INSTANCE.toUserEntity(userInfo);
    userEntity.setNickName(userEntity.getName())
        .setUserType(UserTypeEnum.DEMANDER_USER.getCode())
        .setPassword(PwdUtil.encode(userInfo.getPassword()))
        .setCreateBy(UserUtil.getUsername())
        .setCreateTime(LocalDateTime.now())
        .setUpdateBy(UserUtil.getUsername())
        .setUpdateTime(LocalDateTime.now());
    userService.save(userEntity);
    if (UserTypeEnum.DEMANDER_USER.eq(loginUser.getUserType())) {
      //生成用户公司关系
      companyBusiness.saveUserCompany(userEntity.getUserId(), loginUser.getCompanyId(),
          loginUser.getUserId());
    }
  }

  public void checkUser(UserInfoAdd userInfo) {
    if (StringUtil.isBlank(userInfo.getUserName()) && StringUtil.isBlank(userInfo.getPhone())) {
      throw new ServiceException("用户名或手机号码不能同时为空");
    }
    //校验手机号或者用户名是否被占用
    final List<UserEntity> byUserNameOrMobile = userService.getByUserNameOrMobile(
        userInfo.getUserName(), userInfo.getPhone(), UserTypeEnum.DEMANDER_USER.getCode());
    if (CollUtil.isNotEmpty(byUserNameOrMobile)) {
      throw new ServiceException("用户名或手机号码已被占用,请更换");
    }
    if (StringUtils.isBlank(userInfo.getUserName())) {
      userInfo.setUserName(UserTypeEnum.DEMANDER_USER.userNameByPhone(userInfo.getPhone()));
    }
  }


  public LaborInfoDetail detail(Long userId) {
    final UserEntity userEntity = CommonUtils.requireNotNull(userService.getById(userId),
        "用户Id不存在");
    final LaborInfoDetail laborInfoDetail = UserConverter.INSTANCE.toLaborInfoDetail(userEntity);
    final Map<String, DictDataEntity> dictMapByType = dictBusiness.getMapByType(
        DictTypeEnum.POST.getCode());
    //信息脱敏
    laborInfoDetail.setPhone(UserUtil.desensitize(laborInfoDetail.getPhone()))
        .setIdNumber(UserUtil.desensitize(laborInfoDetail.getIdNumber()));
    //获得评分信息
    final LaborScoreEntity laborScore = scoreBusiness.getByLaborId(laborInfoDetail.getUserId());
    //扩展信息
    final LaborExtEntity extEntity = CommonUtils.requireNotNull(laborExtService.getByUserId(userId),
        "数据有误,请联系管理员");
    if (extEntity != null) {
      laborInfoDetail.setPost1(extEntity.getPost1())
          .setPostName1(getPostName(dictMapByType, extEntity.getPost1()))
          .setPost1Price(extEntity.getPost1Price())
          .setPost1PriceUnit(extEntity.getPost1PriceUnit())
          .setPost2(extEntity.getPost2())
          .setPostName2(getPostName(dictMapByType, extEntity.getPost2()))
          .setPost2Price(extEntity.getPost2Price())
          .setPost2PriceUnit(extEntity.getPost2PriceUnit())
          .setPost3(extEntity.getPost3())
          .setPostName3(getPostName(dictMapByType, extEntity.getPost3()))
          .setPost3Price(extEntity.getPost3Price())
          .setPost3PriceUnit(extEntity.getPost3PriceUnit())
          .setPortfolio(extEntity.getPortfolio())
          .setStartScore(laborScore.getAvgScore())
      ;
    }
    return laborInfoDetail;
  }


  /**
   * 平台我的信息
   *
   * @return
   */
  public PlatformMy platformMyInfo() {
    return new PlatformMy()
        .setCompanyCount(companyBusiness.countCompany())
        .setProjectCount(projectService.getProjectCount())
        .setLaborCount(userService.getLaborCount())
        .setExecutionCount(projectService.getExecutionCount())
        .setPreDeposit(companyAccountBusiness.getPreDepositCurMonth())
        .setPlatformFlows(companyAccountBusiness.getPlatformFlows())
        //.setPlatformPay(productVo.getPlatformPay())
        .setPlatformPay(BigDecimal.ZERO)
        .setBalance(companyAccountBusiness.getBalance())
        .setLockedAmount(companyAccountBusiness.getLockedAmount())
        .setCommission(projectSettleService.getCommission())
        .setLaborApproval(userService.getLaborApproval())
        .setCompanyApproval(companyBusiness.getCompanyApproval())
        ;
  }

  public LaborMy laborMyInfo() {
    final UserInfoModel loginUser = UserUtil.getLoginUser();
    final LaborExtEntity extEntity = laborExtService.getByUserId(loginUser.getUserId());
    final Map<String, DictDataEntity> postMapByType = dictBusiness.getMapByType(
        DictTypeEnum.POST.getCode());
    final LaborAccountEntity userAccount = laborAccountBusiness.getByUserId(loginUser.getUserId());
    return new LaborMy()
        .setUserId(loginUser.getUserId())
        .setName(loginUser.getName())
        .setAuthFlag(loginUser.getAuthFlag())
        .setPost1(extEntity.getPost1())
        .setPost1Name(getPostName(postMapByType, extEntity.getPost1()))
        .setPost2(extEntity.getPost2())
        .setPost2Name(getPostName(postMapByType, extEntity.getPost2()))
        .setPost3(extEntity.getPost3())
        .setPost3Name(getPostName(postMapByType, extEntity.getPost3()))
        .setScheduleList(new ArrayList<>())
        .setCompleteCount(projectLaborBusiness.getCompleteCount())
        .setApplyCount(projectLaborBusiness.getApplyCount())
        .setExecutionCount(projectLaborBusiness.getExecutionCountByUser())
        .setCollectCount(favouriteBusiness.getCollectCount())
        .setRewardCount(laborRewardBusiness.getRewardCount())
        .setIncomeTotal(userAccount.getTotalAmount())
        .setWaitBalance(projectSettleBusiness.sumSettling())
        .setWithdrawBalance(userAccount.getAmount())
        ;
  }

  public DemanderMy demanderMyInfo() {
    final UserInfoModel userInfo = UserUtil.getLoginUser();
    final CompanyEntity company = companyBusiness.getById(userInfo.getCompanyId());
    final CompanyAccountEntity comAccount = companyAccountBusiness.getByComId(company.getComId());
    return new DemanderMy()
        .setCompanyId(userInfo.getCompanyId())
        .setCompanyName(userInfo.getCompanyName())
        .setComStatus(company.getStatus())
        .setCooperationCount(projectService.countForCooperation(userInfo.getUserId()))
        .setVerifyCount(projectService.getDemanderVerifyCount(userInfo.getUserId()))
        .setExecutionCount(projectService.getDemanderExecutionCount(userInfo.getUserId()))
        .setSuddenCount(projectService.projectDemanderSuddenCount(userInfo.getUserId()))
        .setBalance(Objects.isNull(comAccount) ? BigDecimal.ZERO : comAccount.getAmount())
        .setFreezeBalance(Objects.isNull(comAccount) ? BigDecimal.ZERO : comAccount.getLockedAmount())
        .setAvailableBalance(Objects.isNull(comAccount) ? BigDecimal.ZERO : comAccount.getAmount().subtract(comAccount.getLockedAmount()));
  }


  public CommonPageInfo<LaborInfo> listUserNeedCheck(LaborQuery query) {
    final CommonPageInfo<UserEntity> userPage = PageUtils.startPage(query);
    userPage.initData(userService.listUserNeedCheck(query));
    return convert(userPage);
  }

  private CommonPageInfo<LaborInfo> convert(CommonPageInfo<UserEntity> userPage) {
    final CommonPageInfo<LaborInfo> result = userPage.convert(
        UserConverter.INSTANCE::toLaborInfo);
    if (CollUtil.isNotEmpty(result.getList())) {
      final Map<String, DictDataEntity> mapByType = dictBusiness.getMapByType(
          DictTypeEnum.POST.getCode());
      //补充岗位信息
      final List<Long> userIds = result.getList().stream().map(LaborInfo::getUserId)
          .collect(Collectors.toList());
      //获得评分信息
      final Map<Long, LaborScoreEntity> laborScoreMap = scoreBusiness.getLaborScoreMapByLaborIds(
          userIds);
      final Map<Long, LaborExtEntity> extMap = Optional.ofNullable(
          laborExtService.listByUserIds(userIds)).orElseGet(ArrayList::new).stream().collect(
          Collectors.toMap(LaborExtEntity::getUserId, v -> v, (v1, v2) -> v1));
      result.getList().forEach(v -> {
        final LaborExtEntity laborExtEntity = extMap.get(v.getUserId());
        if (laborExtEntity != null) {
          v.setPost1(laborExtEntity.getPost1())
              .setPostName1(getPostName(mapByType, v.getPost1()))
              //.setPost1Price(laborExtEntity.getPost1Price())
              //.setPost1PriceUnit(laborExtEntity.getPost1PriceUnit())
              .setPost2(laborExtEntity.getPost2())
              .setPostName2(getPostName(mapByType, v.getPost2()))
              //.setPost2Price(laborExtEntity.getPost2Price())
              //.setPost2PriceUnit(laborExtEntity.getPost2PriceUnit())
              .setPost3(laborExtEntity.getPost3())
              .setPostName3(getPostName(mapByType, v.getPost3()))
              //.setPost3Price(laborExtEntity.getPost3Price())
              //.setPost3PriceUnit(laborExtEntity.getPost3PriceUnit())
              //.setPortfolio(laborExtEntity.getPortfolio())
              .setStartScore(getStartScore(laborScoreMap, v.getUserId()))
          ;
        }
      });
    }
    return result;
  }

  public CommonPageInfo<UserInfoView> demanderUserManageList(UserQuery query) {
    final CommonPageInfo<UserEntity> userPage = PageUtils.startPage(query);
    userPage.initData(userService.demanderUserManageList(query, UserUtil.getUsername()));
    final CommonPageInfo<UserInfoView> result = userPage.convert(
        UserConverter.INSTANCE::toUserInfoView);
    if (CollUtil.isNotEmpty(userPage.getList())) {
      //补充操作人信息 //补充公司信息
      result.getList().forEach(v ->
          v.setCreateBy(UserUtil.getLoginUser().getName())
              .setCompanyName(UserUtil.getLoginUser().getCompanyName())
      );
    }
    return result;
  }

  public void updatePwd(UpdatePwd updatePwd) {
    //参数判断
    if (StringUtil.isBlank(updatePwd.getOldPwd()) && StringUtil.isBlank(updatePwd.getCheckCode())) {
      throw new ServiceException("请输入旧密码或验证码");
    }
    if (updatePwd.getNewPwd().equals(updatePwd.getConfirmPwd())) {
      throw new ServiceException("两次密码不同");
    }
    final UserEntity userInfo = CommonUtils.requireNotNull(
        userService.getById(UserUtil.getUserId()), "用户不存在");
    if (StringUtils.isNotBlank(updatePwd.getOldPwd())) {
      CommonUtils.assertsTrueWithMessage(
          PwdUtil.encode(updatePwd.getOldPwd()).equals(userInfo.getPassword()), "旧密码错误");
    }
    if (StringUtils.isNotBlank(updatePwd.getCheckCode())) {
      CommonUtils.requireNotNull(userInfo.getPhone(), "未绑定手机");
      checkCodeBusiness.checkCode(userInfo.getPhone(), updatePwd.getCheckCode());
    }
    userInfo.setPassword(PwdUtil.encode(updatePwd.getNewPwd()))
        .setUpdateBy(UserUtil.getUsername())
        .setUpdateTime(LocalDateTime.now());
    userService.updateById(userInfo);
  }
}
